package com.listen.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientUtil;
import com.listen.common.SpecialCharacterHandler;
import com.listen.model.User;

import net.sf.json.JSONObject;

public class Shigongyuan {

	private static final Logger log = LoggerFactory.getLogger(Shigongyuan.class);
	
	final String URL = "http://119.29.22.54:8081";
	
	private String sessionId;
	
	private String _viewstategenerator;
	
	private String _eventvalidation;
	
	private String _viewstate;
	
	private String userid;
	
	private String info;
	
	private ConcurrentHashMap<String, String>  resultMap = null;
	
	public static void main(String[] args) {
		Shigongyuan sgy = new Shigongyuan();
		
		String codes = "";
		//土建施工员10
		sgy.start(codes,"土建施工员",1,30);
		
		//装饰装修施工员11
		codes = "";
		sgy.start(codes,"装饰装修施工员",1,1);
		
		//设备安装施工员12
		codes = "";
		sgy.start(codes,"设备安装施工员",1,1);
		
		//市政工程施工员13
		codes = "360121199802173115";
		sgy.start(codes,"市政工程施工员",18,25);
	}

	
	public void start(String codes,String zyName,int numBegin,int numEnd){
		resultMap = new ConcurrentHashMap<>();
		if(codes.equals("")) return;
		User user = null;
		String zy = "";
		switch(zyName){
		case "土建施工员" : zy = "10";break;
		case "装饰装修施工员" : zy = "11";break;
		case "设备安装施工员" : zy = "12";break;
		case "市政工程施工员" : zy = "13";break;
		}
		String code[] = codes.split(",");
		int length = code.length;
		for(int k = 0;k<length;k++){
			log.info(zyName+"共"+length+"个"+",开始听第"+(k+1)+"个");
			user = new User();
			user.setZy(zy);
			for(int i=numBegin;i<=numEnd;i++){
				user.setAllNum(30);
				user.setCode(code[k]);
				user.setZy(zy);
				user.setZyName(zyName);
				user.setNowNum(i);
				user.setPassword("888888");
				try {
					toLoginPage(user);
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			log.info(zyName+"-第"+(k+1) +"/"+length+"个课程已听完");
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 解析施工员登录页
	 * @param 	loginurl 登录地址
	 * @param	prefixUrl 路径前缀(根路径)
	 */
	private void toLoginPage(User user){
		CloseableHttpResponse response = null;
		try {
			response = HttpClientUtil.getInstance().sendHttpGetResponse(URL + "/Login.aspx?ZY=1");
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
			    _viewstategenerator = parm1.attr("value");
			    Element parm2 = document.getElementById("__EVENTVALIDATION");
			    _eventvalidation = parm2.attr("value");
			    Element parm3 = document.getElementById("__VIEWSTATE");
			    _viewstate = parm3.attr("value");
			    String sessionIdCookie = response.getHeaders("Set-Cookie")[0].getValue();
			    sessionId = sessionIdCookie.substring(0, sessionIdCookie.indexOf(";") + 1);
			    this.login(user);
			}else{
				print(user.getZyName()+"-"+ user.getCode() +" -自动获取登录页面参数失败!");
			}
		} catch (Exception e) {
			printError(user.getCode()+"自动获取登录页面参数异常-->",e);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//智能听课第三步：智能登录
	public void login(User user){
		CloseableHttpResponse response = null;
		String code = user.getCode();
		String zyName = user.getZyName();
		Map<String, String> maps = new ConcurrentHashMap<String, String>();
        maps.put("__VIEWSTATE", _viewstate); 
        maps.put("__VIEWSTATEGENERATOR",_viewstategenerator);
        maps.put("__EVENTVALIDATION",_eventvalidation); 
        maps.put("txtUserName",code);
        maps.put("txtPwd",user.getPassword());
        maps.put("se", "3");
        maps.put("ddlType", "2");
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        
        try {
        	HttpPost httpPost = new HttpPost(URL + "/Login.aspx?ZY=1");// 创建httpPost
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        	httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        	httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        	httpPost.setHeader("Cache-Control", "max-age=0");
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Cookie", sessionId);
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	if(state == 302){
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String userIdCookie = hearders[0].getValue();
        		userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		String infoCookies = hearders[1].getValue();
        		info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
        		openVideo(user);
        	}else{
        		print("登录失败！！！当前账户-"+code+"-所选职业为:"+zyName+",请检查职业是否匹配!");
        	}
		} catch (Exception e) {
			printError("登录异常,当前账户-"+code+"-所选职业为:"+zyName+"异常信息如下：",e);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//打开视频播放界面
	public void  openVideo(User user){
		CloseableHttpResponse response = null;
		String code = user.getCode();
		int i = user.getNowNum();
		String id = i <10 ? "0000" + i : "000" + i;
		String vcodeJson = "{Vcode:\"" + id + "\"}";
		String openUrl = URL + "/StudentClass/shipinSection.aspx/CheckCanWatch?dt="+ SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
		String cookies = sessionId + userid + info +" RID="+id +"; id="+id;
		try {
			HttpPost httpPost = new HttpPost(openUrl);// 创建httpPost
			httpPost.setHeader("Accept","application/json, text/javascript, */*; q=0.01");
			httpPost.setHeader("Accept-Encoding","gzip, deflate");
			httpPost.setHeader("Accept-Language","zh-CN,zh;q=0.9");
			httpPost.setHeader("Cookie", cookies);
			httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
			httpPost.setHeader("X-Requested-With","XMLHttpRequest");
			response = HttpClientUtil.getInstance().sendHttpPost(httpPost, vcodeJson);
			int state = response.getStatusLine().getStatusCode();
			String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			if(state == 200){
				String msg = (String) JSONObject.fromObject(entityStr).get("d");
				System.out.println(msg);
				if("".equals(msg)){
					submitListen(user);
				}else{
					print(user.getZyName() + "-"+code +"-第"+ i +"打开视频播放界面异常："+msg);
				}
			}else{
				print(user.getZyName() + "-"+code +"-第"+ i +"打开视频播放界面失败，状态："+state);
			}
		} catch (Exception e) {
			printError("打开视频播放界面异常,当前账户-"+code+"-所选职业为:"+user.getZyName()+"异常信息如下：",e);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//提交听课单
	public void submitListen(User user){
		CloseableHttpResponse response = null;
		String code = user.getCode();
		int i = user.getNowNum();
		String id = i < 10 ? "0000" + i : "000" + i;
		String rvCodeJson = "{RVCode:\"" + i + "\"}";
		String listenUrl = URL + "/StudentClass/WatchVideo.aspx/UpdateStudyType?dt="+ SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
		String url =  URL + "/StudentClass/WatchVideo.aspx?ids="+id;
		url = SpecialCharacterHandler.replaceAll(url);
		String uid = userid.split("=")[1];
		String date = DateFormatUtil.getDateStr(new Date());
		String st = SpecialCharacterHandler.replaceAll(date);
		String cookies = sessionId + userid + info +" RID="+id +"; id="+id +"; url="+url +"; checkUid="+ uid +"; st="+ st +"; totaltime=2314;nowtime=2261";
		//System.out.println(cookies);
		try {
			HttpPost httpPost = new HttpPost(listenUrl);// 创建httpPost
			httpPost.setHeader("Accept","application/json, text/javascript, */*; q=0.01");
			httpPost.setHeader("Accept-Encoding","gzip, deflate");
			httpPost.setHeader("Accept-Language","zh-CN,zh;q=0.9");
			httpPost.setHeader("Cookie", cookies);
			httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
			httpPost.setHeader("X-Requested-With","XMLHttpRequest");
			response = HttpClientUtil.getInstance().sendHttpPost(httpPost, rvCodeJson);
			int state = response.getStatusLine().getStatusCode();
			String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			if(state == 200){
				String msg = (String) JSONObject.fromObject(entityStr).get("d");
				print(user.getZyName() + "-"+ code +"-第"+ i +"个视频"+msg);
			}else{
				print(user.getZyName() + "-"+ code +"-第"+ i +"视频播放失败!"+entityStr);
			}
		} catch (Exception e) {
			printError(user.getZyName() +"-"+ code +"-第" +i +" 视频听课异常--->",e);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
		logout(user);
	}
	
	public void logout(User user){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		String zy = user.getZy();
		String zyName = user.getZyName();
		String code = user.getCode();
		try {
			String path = URL  + "/Public/Logout.aspx?id="+zy;
			httpGet = new HttpGet(path);
			String cookie = sessionId + userid + info +" totaltime=2281; checkUid="+userid+"; nowtime=2281";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				//log.info(zyName+"-"+code+"-退出登录成功!");
			}else{
				log.info(zyName+"-"+code+"-退出登录失败!");
			}
		} catch (Exception e) {
			printError(zyName+code+"退出登录错误--->",e);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	private void print(String msg){
		resultMap.put("msg", msg);
		log.info(msg);
	}
	
	private void printError(String msg,Exception e){
		msg = msg + e.getMessage();
		resultMap.put("msg", msg);
		log.info(msg,e);
	}
}
